// generateView.js
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const util = require('util')
const resolve = (...file) => path.resolve(__dirname, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
const { vueTemplate } = require('./template/view')
const { cssTemplate } = require('./template/css')
const { routerTemplate } = require('./template/router') // 获取路由模板
const { apiTemplate } = require('./template/api') 

//生成view视图文件
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`)
    return
  }
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', err => {
      if (err) {
        errorLog(err.message)
        reject(err)
      } else {
        resolve(true)
      }
    })
  })
}

const generateRouter = (path,frompath) => {
  const files = fs.readdirSync(path);
  const fileReg = /\./;
  const reg = /\.(vue)$/;
  const routes = []
  const requireComponent = []
  files.forEach((file) => {
        if (fileReg.test(file)) { // 判断是否为文件
          if (reg.test(file)) { // 判断是否为指定文件
            
          }
        } else{
          const name = file.replace(reg, "")
          routes.push(name)
        }
    })
  return new Promise((resolve, reject) => {
      fs.writeFile(frompath, routerTemplate(routes), 'utf8', err => {
        if (err) {
          errorLog(err.message)
          reject(err)
        } else {        
          resolve(true)       
        }
      })
  })
}

const generateApi = (apiUrl,options) => {
  return new Promise((resolve, reject) => {
      fs.appendFile(apiUrl, apiTemplate(options), err => {
        if (err) {
          errorLog(err.message)
          reject(err)
        } else {        
          resolve(true)       
        }
      })
  })
}

log('请输入要生成的页面组件名称,会生成在 views/目录下')
let options = {
  componentName:'',
  viewName : 'index'
}
process.stdin.on('data', async chunk => {
  const inputName = String(chunk).trim().toString()
  /**
   * Vue页面组件路径
   */
  let routerList = resolve('../src/views')
  let routerUrl =  resolve('../src/router/router.js')
  let apiUrl = resolve('../src/api/api.js')
  let componentVueName = resolve('../src/views/' + inputName, options.viewName)
  // 如果不是以 .vue 结尾的话，自动加上
  if (!componentVueName.endsWith('.vue')) {
    componentVueName += '.vue'
  }

  let componentCssName = resolve('../src/views/' + inputName, options.viewName)
  // 如果不是以 .vue 结尾的话，自动加上
  if (!componentCssName.endsWith('.less')) {
    componentCssName += '.less'
  }
  /**
   * vue组件目录路径
   */
  const componentDirectory = path.dirname(componentVueName)

  const hasComponentExists = fs.existsSync(componentVueName)
  if (hasComponentExists) {
    errorLog(`${inputName}页面组件已存在，请重新输入`)
    return
  } else {
    log(`正在生成 vue 目录 ${componentDirectory}`)
    await dotExistDirectoryCreate(componentDirectory)
  }
  try {
    if (inputName.includes('/')) {
      const inputArr = inputName.split('/')
      options.componentName = inputArr[inputArr.length - 1]
    } else {
      options.componentName = inputName
    }
    log(`正在生成 vue 文件 ${componentVueName}`)
    await generateFile(componentVueName, vueTemplate(options))
    successLog('生成成功')
    log(`正在生成 css 文件 ${componentCssName}`)
    await generateFile(componentCssName, cssTemplate(options))
    successLog('生成成功')
    log(`正在生成 router 文件 ${routerUrl}`)
    await generateRouter(routerList,routerUrl)
    successLog('生成成功')
    log(`正在生成 api 文件 ${apiUrl}`)
    await generateApi(apiUrl,options)
    successLog('生成成功')
  } catch (e) {
    errorLog(e.message)
  }
  process.stdin.emit('end')
})
process.stdin.on('end', () => {
  log('exit')
  process.exit()
})
function dotExistDirectoryCreate (directory) {
  return new Promise((resolve) => {
    mkdirs(directory, function () {
      resolve(true)
    })
  })
}

// 递归创建目录
function mkdirs (directory, callback) {
  var exists = fs.existsSync(directory)
  if (exists) {
    callback()
  } else {
    mkdirs(path.dirname(directory), function () {
      fs.mkdirSync(directory)
      callback()
    })
  }
}


function reatdDrir(path, reg) { // path 读取的目录， reg 文件匹配的正则 返回一个 读取完的数组
  const result = [];
  _reatdDir(path, reg, result);
  log(result);
  return result;
}
